package l2ft.gameserver.model.items;

import java.util.Collection;

import l2ft.commons.dao.JdbcEntityState;
import l2ft.gameserver.dao.ItemsDAO;
import l2ft.gameserver.model.entity.auction.Auction;
import l2ft.gameserver.model.items.ItemInstance.ItemLocation;

public class AuctionStorage extends ItemContainer
{
	private static final ItemsDAO _itemsDAO = ItemsDAO.getInstance();
	private static AuctionStorage _instance;

	protected AuctionStorage()
	{
		restore();
	}

	public void addNewAuction(Auction auction)
	{
		onAddItem(auction.getItem());
	}
	
	public void deleteItemFromList(ItemInstance item)
	{
		_items.remove(item);
	}
	
	@Override
	protected void onAddItem(ItemInstance item)
	{
		item.setLocation(getItemLocation());
		item.setLocData(0);
		if(item.getJdbcState().isSavable())
		{
			item.save();		
		}
		else
		{
			item.setJdbcState(JdbcEntityState.UPDATED);
			item.update();
		}
	}

	@Override
	protected void onModifyItem(ItemInstance item)
	{
		item.setJdbcState(JdbcEntityState.UPDATED);
		item.update();
	}

	@Override
	protected void onRemoveItem(ItemInstance item)
	{
		item.setLocData(-1);
	}

	@Override
	protected void onDestroyItem(ItemInstance item)
	{
		item.setCount(0L);
		item.delete();
	}

	public ItemLocation getItemLocation()
	{
		return ItemLocation.AUCTION;
	}

	public void restore()
	{
		writeLock();
		try
		{
			_items.clear();
			Collection<ItemInstance> items = _itemsDAO.getItemsByLocation(ItemLocation.AUCTION);
			
			for(ItemInstance item : items)
			{
				_items.add(item);
			}
		}
		finally
		{
			writeUnlock();
		}
	}
	
	public static AuctionStorage getInstance()
	{
		if(_instance == null)
			_instance = new AuctionStorage();
		return _instance;
	}
}